{"cells":[{"attachments":{},"cell_type":"markdown","metadata":{"id":"11n5gndbRzoY"},"source":["# Flow Control"]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"AIFsv_RZ1iV0"},"source":["\n"," \n"," \n","
\n"," \"Open\n"," \n"," \n","
"]},{"cell_type":"markdown","metadata":{"id":"SwFKFBMwRzoa"},"source":["## Introduction"]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"Ss9hRGHDRzob"},"source":["Last week, we learned the basics of individual instructions and that a program is just a series of instructions. But programming’s real strength isn’t just running one instruction after another. Based on how expressions evaluate, a program can decide to skip instructions, repeat them, or choose one of several instructions to run. In fact, you rarely want your programs to start from the first line of code and simply execute every line straight to the end. **Flow control statements** can decide which Python instructions to execute under which conditions."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["These flow control statements directly correspond to the symbols in a flowchart. A flowchart usually has more than one way to go from the start to the end. The same is true for lines of code in a computer program. Flowcharts represent these branching points with diamonds, while the other steps (states) are represented with rectangles. The starting and ending steps are represented with rounded rectangles."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["
\n","
source: https://automatetheboringstuff.com/2e/chapter2/
"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["But before you learn about flow control statements, you first need to learn how to represent those **yes** and **no** options and understand how to write those **branching** points as Python code. To that end, let’s explore Boolean values, comparison operators, and Boolean operators."]},{"cell_type":"markdown","metadata":{"id":"WjPuxQq1sA-3"},"source":["### Boolean expressions"]},{"cell_type":"markdown","metadata":{"id":"TVuZi_rfsC9u"},"source":["A boolean expression is an expression that is either true or false. The following examples use the operator `==`, which compares two operands and produces `True` if they are equal and `False` otherwise:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":268,"status":"ok","timestamp":1665656455180,"user":{"displayName":"phonchi chung","userId":"13517391734500420886"},"user_tz":-480},"id":"QYptoP__sAbn","outputId":"509e26a1-7d5a-45c8-fd10-e7fa4ce694ec"},"outputs":[],"source":["5 == 5, 5 == 6"]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"cc7LkxgesPQf"},"source":["`True` and `False` are special values that belong to the class `bool`; they are not strings:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":3,"status":"ok","timestamp":1665656388598,"user":{"displayName":"phonchi chung","userId":"13517391734500420886"},"user_tz":-480},"id":"9eio5IH1sRe_","outputId":"10691270-f0b2-4cac-c7a1-b0e286eedbd0"},"outputs":[],"source":["type(True), type(False)"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["The `==` operator is one of the ***comparison operators*** or relational operators; the others are:"]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"DoBusgVgs4sP"},"source":["| | Meaning |\n","|------------|---------------------------------|\n","| x != y | x is not equal to y |\n","| x > y | x is greater than y |\n","| x < y | x is less than y |\n","| x >= y | x is greater than or equal to y |\n","| x <= y | x is less than or equal to y |\n","| x is y | x is the same as y |\n","| x is not y | x is not the same as y |"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["> The `Python` symbols are different from the mathematical symbols for the same operations. A common error is to use a single equal sign `=` instead of a double equal sign `==`. Remember that `=` is used in the assignment statement and `==` is a comparison operator. There is no such thing as `=<` or `=>`."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["These operators evaluate to `True` or `False` depending on the values you give them and, therefore, can be used in the decision point as a condition statement."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["print(42==42)\n","print(42==42.0) # It will compare its value!\n","print(42=='42') # int/float are always different from string\n","print(2!=3)\n","print('hello'=='Hello') # Python is case sensitive\n","print(42 < 100)\n","print(42 >= 100)"]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"vk4VMOiLBn7L"},"source":["### Boolean (Logical) Operators"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["The three Boolean operators (`and`, `or`, and `not`) are used to operate on Boolean values. Like comparison operators, they evaluate these expressions down to a Boolean value. Let’s explore these operators in detail."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["| Expression | Evaluates to . . . | \n","|-----------------|--------------------|\n","| True and True | True |\n","| True and False | False |\n","| False and True | False |\n","| False and False | False |"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["| Expression | Evaluates to . . . |\n","|----------------|--------------------|\n","| True or True | True |\n","| True or False | True |\n","| False or True | True |\n","| False or False | False |"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["| Expression | Evaluates to . . . |\n","|------------|--------------------|\n","| not True | False |\n","| not False | True |"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["print((4 < 5) and (5 < 6))\n","print((6 < 5) or (9 < 6))\n","print((1 == 2) or (2 == 2))\n","print(not (1==3) and (3==4))"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["The computer will evaluate the left expression first, and then it will evaluate the right expression. When it knows the Boolean value for each, it will then evaluate the whole expression down to one Boolean value. The Boolean operators have an order of operations just like the math operators do. After any math and comparison operators evaluate, Python evaluates the `not` operators first, then the and operators, `and` then the `or` operators."]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"_6ZotSZXEzN5"},"source":["## Elements of Flow Control"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["It can be shown that all programs could be written using three forms of control—namely, **sequential execution, the selection statement and the repetition statement**. This is the idea behind ***structured programming***.\n","\n","Flow control statements often start with a part called the ***condition*** and are always followed by a block of code called the ***clause*** or body. The Boolean expressions you’ve seen so far could all be considered conditions, which are the same thing as expressions; the condition is just a more specific name in the context of flow control statements. Conditions always evaluate down to a Boolean value, `True` or `False`. A flow control statement decides what to do based on whether its condition is `True` or `False`."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### Blocks of Code"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["Lines of Python code can be grouped together in ***blocks***. You can tell when a block begins and ends from the *indentation* of the lines of code. There are three rules for blocks.\n","\n","1. Blocks begin when the indentation increases.\n","2. Blocks can contain other blocks.\n","3. Blocks end when the indentation decreases to zero or to a containing block’s indentation.\n","\n","Blocks are easier to understand by looking at some indented code, so let’s find the blocks in part of a small game program, shown here:"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["name = 'Mary'\n","password = 'swordfish'\n","if name == 'Mary':\n"," print('Hello, Mary')\n"," if password == 'swordfish':\n"," print('Access granted.')\n"," else:\n"," print('Wrong password.')"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["You can view the execution of this program at https://autbor.com/blocks/. The first block of code starts at the line `print('Hello, Mary')` and contains all the lines after it. Inside this block is another block, which has only a single line in it: `print('Access Granted.')`. The third block is also one line long: `print('Wrong password.')`."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["An `IndentationError` occurs if you have more than one statement in a block and those statements do not have the same indentation:"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["name = 'Mary'\n","password = 'swordfish'\n","if name == 'Mary':\n"," print('Hello, Mary')\n"," if password == 'swordfish':\n"," print('Access granted.')\n"," else:\n"," print('Wrong password.')"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["> It is recomend to use **four white spaces** as the indentation"]},{"cell_type":"markdown","metadata":{"id":"1NUilGNt2iJS"},"source":["### Conditional execution"]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"U_5LmIfNE165"},"source":["The control statement affords us a mechanism for jumping from one part of a program to another. In higher-level languages like Python, this enables what is called **control structures**, syntax patterns that allow us to express algorithms more succinctly. One example of this is the **if-statement**. An `if` statement’s body (that is, the block following the `if` statement) will execute if the statement’s condition is `True`. The body is skipped if the condition is `False`."]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"eLp7j4ueFK4h"},"source":["In Python, an `if` statement consists of the following:\n","\n","- The `if` keyword\n","- A condition (that is, an expression that evaluates to `True` or `False`)\n","- A colon\n","- Starting on the next line, an indented block of code (called the `if` body)\n","\n","The boolean expression after the `if` statement is called the condition. We end the `if` statement with a colon character (`:`) and the line(s) after the `if` statement are indented. If the logical condition is true, then the indented statement gets executed. If the logical condition is false, the indented statement is skipped."]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":429,"status":"ok","timestamp":1665387208888,"user":{"displayName":"phonchi chung","userId":"13517391734500420886"},"user_tz":-480},"id":"OLi_7GqcRzox","outputId":"50ce1edb-f501-4b8b-f3d8-9e95e748c2ce"},"outputs":[],"source":["name = 'Mary'\n","if name == 'Alice':\n"," print('Hi, Alice.')"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["
\n","
source: https://automatetheboringstuff.com/2e/chapter2/
"]},{"cell_type":"markdown","metadata":{"id":"i7wWs6bj1CeU"},"source":["A second form of the `if` statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":2,"status":"ok","timestamp":1665387517163,"user":{"displayName":"phonchi chung","userId":"13517391734500420886"},"user_tz":-480},"id":"j3ALfiYq1KNJ","outputId":"ef0ee27a-f6d7-4734-90dc-97fd8b01e537"},"outputs":[],"source":["if name == 'Alice':\n"," print('Hi, Alice.')\n","else:\n"," print('Hello, stranger.')"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["You can also write the above code in one line using the ***ternary conditional operator***:"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["print('Hi, Alice.') if name == 'Alice' else print('Hello, stranger.') # Note that we do not have colon in between!"]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"wS5jvy7X1VNY"},"source":["
\n","
source: https://automatetheboringstuff.com/2e/chapter2/
"]},{"cell_type":"markdown","metadata":{"id":"Lk7kiHwr1hEh"},"source":["Since the condition must either be true or false, exactly one of the alternatives will be executed. The alternatives are called ***branches***, because they are branches in the flow of execution."]},{"cell_type":"markdown","metadata":{"id":"PCLnLflt1rZR"},"source":["Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":2,"status":"ok","timestamp":1665387694945,"user":{"displayName":"phonchi chung","userId":"13517391734500420886"},"user_tz":-480},"id":"NtHQJ54h1yTp","outputId":"3af6417b-88d9-4398-8fdb-0aee8cb71de2"},"outputs":[],"source":["name = 'Carol'\n","age = 3000\n","if name == 'Alice':\n"," print('Hi, Alice.')\n","elif age < 12:\n"," print('You are not Alice, kidd.')\n","else:\n"," print('You are neither Alice nor a little kid.')"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["You can view the execution of this program at https://autbor.com/littlekid/. In plain English, this type of flow control structure would be “If the first condition is true, do this. Else, if the second condition is true, do that."]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"YzlT65M418D5"},"source":["
\n","
source: https://automatetheboringstuff.com/2e/chapter2/
"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["> ### Exercise 1: Write a code that allows the user to input `row` and `column`. The program prints 'black' or 'white' depending on the color of the specified row and column of the chessboard. Chess boards are 8 x 8 spaces in size, and the rows and columns in this program begin at 0 and end at 7. If the inputs for a row or column are outside the 0 to 7 range, it should print 'out of board'!"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["
\n","
source: https://inventwithpython.com/pythongently/images/image011.png
"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["row = int(input(\"Enter row\"))\n","column = int(input(\"Enter column\"))\n","# If the column and row is out of bounds, print out of board:\n","if column ____ or column ___ or row ___ or row ____:\n"," print('out of board')\n","# If the even/oddness of the column and row match, print 'white':\n","____ column % _ == row % _:\n"," print('white')\n","# If they don't match, then print 'black':\n","____:\n"," print('black')"]},{"cell_type":"markdown","metadata":{"id":"ydjopqnU2n_R"},"source":["### Loops and Iterations"]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"7EvWoL27Fbqx"},"source":["You can make a block of code execute over and over again using a `while` statement. The code in a `while` body will be executed as long as the `while` statement’s condition is `True`. In code, a `while` statement always consists of the following:\n","\n","- The `while` keyword\n","- A condition (that is, an expression that evaluates to `True` or `False`)\n","- A colon\n","- Starting on the next line, an indented block of code (called the `while` body)"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":2,"status":"ok","timestamp":1665382029603,"user":{"displayName":"phonchi chung","userId":"13517391734500420886"},"user_tz":-480},"id":"mJnA-rQOFIAm","outputId":"9c888db1-27fd-4f47-a04a-0aa1da02ba4d"},"outputs":[],"source":["spam = 0\n","while spam < 5:\n"," print('Hello, world.')\n"," spam += 1 # equivalent to spam = spam + 1"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["> ***Augmented assignments*** abbreviate assignment expressions in which the same variable name appears on the left and right of the assignment’s `=` as above"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["
\n","
source: https://automatetheboringstuff.com/2e/chapter2/
"]},{"cell_type":"markdown","metadata":{"id":"bXzLhOOb27tS"},"source":["More formally, here is the flow of execution for a `while` statement:\n","\n","1. Evaluate the condition, yielding `True` or `False`.\n","\n","2. If the condition is false, exit the `while` statement and continue execution at the next statement.\n","\n","3. If the condition is true, execute the body and then go back to step 1."]},{"attachments":{},"cell_type":"markdown","metadata":{"id":"MLdwEwBq3N4B"},"source":["In the `while` ***loop***, the condition is always checked at the start of each ***iteration*** (that is, each time the loop is executed). If the condition is `True`, then the body is executed, and afterward, the condition is checked again. The first time the condition is found to be `False`, the while body is skipped."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["A common programming pattern is that we can run the program as long as the user wants by putting most of the program in a `while` loop. We’ll define a quit value and then keep the program running as long as the user has not entered the quit value:"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["prompt = \"\\nTell me something, and I will repeat it back to you:\"\n","prompt += \"\\nEnter 'quit' to end the program. \"\n","message = \"\"\n","while message != 'quit':\n"," message = input(prompt)\n"," print(message)"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["We first set up a variable `message` to keep track of whatever value the user enters. We define `message` as an empty string, `\"\"`, so Python has something to check the first time it reaches the while line. The first time through the loop, the message is just an empty string, so Python enters the loop. At `message = input(prompt)`, Python displays the prompt and waits for the user to enter their input. Whatever they enter is assigned to `message` and printed; then, Python reevaluates the condition in the `while` statement. As long as the user has not entered the word 'quit', the prompt is displayed again and Python waits for more input. When the user finally enters 'quit', Python stops executing the while loop and the program ends."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["> Note that Python considers `0`, `None`, empty string, and empty container as `False` and all other things are `True`!"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["bool(\"\"), bool(0), bool(None), bool(prompt), bool(12)"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["#### Using `break` to Exit a Loop"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["The above program works well, except that it prints the word 'quit' as if it were an actual message. In fact, there is a shortcut to getting the program execution to break out of a `while` loop’s body early. If the execution reaches a `break` statement, it immediately exits the while loop’s body. In code, a `break` statement simply contains the `break` keyword."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["prompt = \"\\nTell me something, and I will repeat it back to you:\"\n","prompt += \"\\nEnter 'quit' to end the program. \"\n","message = \"\"\n","while True:\n"," message = input(prompt)\n"," if message == 'quit':\n"," break\n"," else:\n"," print(message)"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["The fourth line creates an ***infinite loop***; it is a `while` loop whose condition is always `True`. After the program execution enters this loop, it will exit the loop only when a `break` statement is executed. (An infinite loop that never exits is a common programming bug.)\n","\n","Just like before, this program asks the user to for the input. Now, however, while the execution is still inside the `while` loop, an `if` statement checks whether the `message` is equal to 'quit'. If this condition is `True`, the `break` statement is run, and the execution moves out of the loop. Otherwise, the `if` statement’s body that contains the `break` statement is skipped, which again prints out the `message`. After that, the program execution jumps back to the start of the `while` statement to recheck the condition. Since this condition is merely the `True` Boolean value, the execution enters the loop to ask the user to type another message."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["#### `continue` Statemet"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["Rather than breaking out of a loop entirely without executing the rest of its code, you can use the `continue` statement to return to the beginning of the loop based on the result of a conditional test. For example, consider a loop that counts from 1 to 10 but prints only the odd numbers in that range:"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["current_number = 0\n","while current_number < 10:\n"," current_number += 1\n"," if current_number % 2 == 0:\n"," continue\n"," else:\n"," print(current_number, end=' ')"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["First, we set `current_number` to 0. Because it’s less than 10, Python enters the while loop. Once inside the loop, we increment the count by 1, so `current_number` is 1. The `if` statement then checks the modulo of `current_number` and 2. If the modulo is 0, the `continue` statement tells Python to ignore the rest of the loop and return to the beginning. If the `current_number` is not divisible by 2, the rest of the loop is executed and Python prints the `current_number`."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["Note that the built-in function `print()` displays its argument(s), then moves the cursor to the next line. You can change this behavior with the argument `end`. We used one space (' '), so each call to print displays the character’s value followed by one space."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["> If you ever run a program that has a bug causing it to get stuck in an infinite loop, press CTRL-C. This will send a `KeyboardInterrupt` error to your program and cause it to stop immediately."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["#### “TRUTHY” and “FALSY” Values"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["Let us delve into the following program:"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["name = ''\n","while not name:\n"," print('Enter your name:')\n"," name = input()\n","\n","print('How many guests will you have?')\n","numOfGuests = int(input())\n","\n","if numOfGuests:\n"," print('Be sure to have enough room for all your guests.')\n","print('Done')"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["You can view the execution of this program at https://autbor.com/howmanyguests/. If the user enters a blank string for name, then the `while` statement’s condition will be `True`, and the program continues to ask for a name. If the value for `numOfGuests` is not `0`, then the condition is considered to be `True`, and the program will print a reminder for the user. You could have entered `not name != ''` instead of `not name`, and `numOfGuests != 0` instead of `numOfGuests`, but using the truthy and falsy values can make your code easier to read."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### `for` Loops and the `range()` Function"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["The `while` loop keeps looping `while` its condition is `True` (which is the reason for its name), but what if you want to execute a block of code **only a certain number of times**? You can do this with a `for` loop statement and the `range()` function."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["In code, a `for` statement looks something like `for i in range(5)`: and includes the following:\n","\n","- The `for` keyword\n","- A variable name\n","- The `in` keyword\n","- A call to the `range()` funtion with up to three integers passed to it (or an `iterable` object, which we will discuss later on)\n","- A colon\n","- Starting on the next line, an indented block of code (called the for body)\n","\n","Let’s create a new program to help you see a `for` loop in action."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["print('My name is')\n","for i in range(5):\n"," print('Jimmy Five Times (' + str(i) + ')')"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["You can view the execution of this program at https://autbor.com/fivetimesfor/. The code in the `for` loop’s body is run five times. The first time it is run, the variable `i` is set to 0. The `print()` call in the body will print Jimmy Five Times (0). After Python finishes an iteration through all the code inside the `for` loop’s body, the execution goes back to the top of the loop, and the `for` statement increments `i` by one. This is why `range(5)` results in five iterations through the body, with `i` being set to 0, then 1, then 2, then 3, and then 4. The variable `i` will go up to, but will not include, the integer passed to `range()`. "]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["You can actually use a `while` loop to do the same thing as a `for` loop; `for` loops are just more concise."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["print('My name is')\n","i = 0\n","while i < 5:\n"," print('Jimmy Five Times (' + str(i) + ')')\n"," i = i + 1"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["#### The Starting, Stopping, and Stepping Arguments to `range()`"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["Some functions can be called with multiple arguments separated by a comma, and `range()` is one of them. This lets you change the integer passed to `range()` to follow any sequence of integers, including starting at a number other than zero."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["for i in range(12, 16):\n"," print(i)"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["The `range()` function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["for i in range(0, 10, 2):\n"," print(i)"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["The `range()` function is flexible in the sequence of numbers it produces for `for` loops. For example , you can even use a **negative number** for the step argument to make the `for` loop count down instead of up."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["for i in range(5, -1, -1):\n"," print(i)"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["> Note that Python introduce [switch](https://learnpython.com/blog/python-match-case-statement/) statement as another control statement in Python 3.10 "]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["> ### Exercise 2: Write a script that displays the following triangle patterns. Use `for` loops to generate the patterns. \n","\n","```\n","*\n","**\n","***\n","****\n","*****\n","******\n","*******\n","********\n","*********\n","**********\n","```\n","\n","Hint: Try to use nested loops and use the outer loop to display each row while the inner loop to display each column"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["for row in range(__,__):\n"," for column in range(__,__):\n"," print('*', end='')\n"," print()"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["## Importing Modules"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["All Python programs can call a basic set of functions called built-in functions, including the `print()`, `input()`, `len()` and `range()` functions you’ve seen before. Python also comes with a set of modules called the **standard library**. Each module is a Python program that contains a related group of functions that can be embedded in your programs. For example, the `math` module has mathematics-related functions. The `random` module has random number-related functions, and so on.\n","\n","Before you can use the functions in a module, you must ***import*** the module with an `import` statement. In code, an `import` statement consists of the following:\n","\n","- The `import` keyword\n","- The name of the module\n","- Optionally, more module names, as long as they are separated by commas\n","\n","Once you import a module, you can use all the cool functions of that module. Let’s give it a try with the `random` module, which will give us access to the `random.randint()` function."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["import random\n","for i in range(5):\n"," print(random.randint(1, 10))"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["You can view the execution of this program at https://autbor.com/printrandom/. The `random.randint()` function call evaluates to a random integer value between the two integers that you pass it. Since `randint()` is in the `random` module, you must first type `random.` in front of the function name to tell Python to look for this function inside the `random` module. We will discuss it more in the following chapter."]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["> Check out the Python standard library [here](https://docs.python.org/3/library/index.html#library-index) or [here](https://pymotw.com/3/index.html)"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### Ending a Program Early with the `sys.exit()` Function"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["The last flow control concept to cover is how to terminate the program. Programs always terminate if the program execution reaches the bottom of the instructions. However, you can cause the program to terminate, or exit, before the last instruction by calling the `sys.exit()` function. Since this function is in the `sys` module, you have to `import sys` before your program can use it."]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["%%writefile exit.py\n","\n","import sys\n","\n","while True:\n"," print('Type exit to exit.')\n"," response = input()\n"," if response == 'exit':\n"," sys.exit()\n"," print('You typed ' + response + '.')\n","print('This line will not be printed')"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["%run exit.py"]},{"attachments":{},"cell_type":"markdown","metadata":{},"source":["By using expressions that evaluate to `True` or `False` (also called conditions), you can write programs that make decisions on what code to execute and what code to skip. You can also execute code over and over again in a loop while a certain condition evaluates to `True`. The `break` and `continue` statements are useful if you need to exit a loop or jump back to the loop’s start. These flow control statements will let you write more intelligent programs. You can also use another type of flow control by **writing your own functions**, which is the topic of the next chapter."]}],"metadata":{"colab":{"provenance":[]},"kernelspec":{"display_name":"base","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.8.8"},"vscode":{"interpreter":{"hash":"ffe9a5d1be64f395cda62646beb00f4fbc1d5c319e2b42024d6d4b4beddf19a5"}}},"nbformat":4,"nbformat_minor":0}